package com.itbupt.infrastructure.event;

import com.alibaba.fastjson.JSON;
import com.itbupt.types.event.BaseEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author dingchang
 * @Date 2025/3/31 16:36
 * @Description: 消息发送模块 - 生产者 - 用于发送消息到RabbitMQ
 */

@Slf4j
@Component
public class EventPublisher {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 向指定的topic发送消息
     * @param topic 主题
     * @param eventMessage 消息体
     */
    public void publish(String topic, BaseEvent.EventMessage<?> eventMessage) {
        try {
            // 将消息体转换为JSON格式
            String messageJson = JSON.toJSONString(eventMessage);
            // 发送消息到RabbitMQ指定的topic
            rabbitTemplate.convertAndSend(topic, messageJson);

            log.info("发送MQ消息 topic:{} message:{}", topic, messageJson);

        } catch (Exception e) {

            log.error("发送MQ消息失败 topic:{} message:{}", topic, JSON.toJSONString(eventMessage), e);
            throw e;
        }
    }

    public void publish(String topic, String eventMessageJSON){
        try {
            rabbitTemplate.convertAndSend(topic, eventMessageJSON);
            log.info("发送MQ消息 topic:{} message:{}", topic, eventMessageJSON);
        } catch (Exception e) {
            log.error("发送MQ消息失败 topic:{} message:{}", topic, eventMessageJSON, e);
            throw e;
        }
    }

}
